<template>
    <div class="order-detail-container" style="margin-bottom: 50px; padding-bottom: 10px;">
        <van-nav-bar title="订单详情" left-text="" left-arrow fixed @click-left="onClickLeft">
            <template #left>
                <van-icon name="arrow-left" size="24" color="gray" />
            </template>
        </van-nav-bar>

        <div class="content">
            <!-- 加载状态 -->
            <div v-if="isLoading" class="loading-container">
                <van-loading type="spinner" color="#4f46e5" />
                <p class="loading-text">正在加载订单信息...</p>
            </div>

            <!-- 订单信息，仅在非加载状态显示 -->
            <template v-else>
                <!-- 订单状态 -->
                <div class="status-card">
                    <div class="status-info">
                        <div class="status-icon" :class="getOrderStatusClass(orderInfo.orderStatus)">
                            <van-icon :name="getOrderStatusIcon(orderInfo.orderStatus)" />
                        </div>
                        <div class="status-details">
                            <h3 class="status-title">{{ getOrderStatusText(orderInfo.orderStatus) }}</h3>
                            <p class="status-desc">{{ getOrderStatusDescription(orderInfo.orderStatus) }}</p>
                        </div>
                    </div>
                </div>

                <!-- 任务信息 -->
                <div class="order-card">
                    <h2 class="section-title">任务信息</h2>
                    <div class="order-info">
                        <div class="task-info">
                            <div class="flex justify-between items-start mb-2">
                                <h3 class="task-title">{{ orderInfo.taskTitle }}</h3>
                                <span class="task-price">¥{{ orderInfo.orderAmount }}</span>
                            </div>
                            <p class="task-address">{{ orderInfo.taskAddress }}</p>
                            <div class="task-time">
                                <span class="time-item"><van-icon name="calendar-o" /> {{ orderInfo.taskDate }}</span>
                                <span class="time-item"><van-icon name="clock-o" /> {{ orderInfo.taskTime }}</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 订单详情 -->
                <div class="order-card">
                    <h2 class="section-title">订单详情</h2>
                    <div class="order-info">
                        <div class="detail-item">
                            <span class="detail-label">订单编号</span>
                            <span class="detail-value">{{ orderInfo.orderId }}</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">创建时间</span>
                            <span class="detail-value">{{ formatDateTime(orderInfo.createTime) }}</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">支付状态</span>
                            <span class="detail-value">
                                <van-tag plain :type="getPaymentStatusType(orderInfo.paymentStatus)">
                                    {{ getPaymentStatusText(orderInfo.paymentStatus) }}
                                </van-tag>
                            </span>
                        </div>
                        <div class="detail-item" v-if="orderInfo.orderStatus === -1">
                            <span class="detail-label">取消原因</span>
                            <span class="detail-value">{{ orderInfo.cancelReason || '无' }}</span>
                        </div>
                    </div>
                </div>

                <!-- 价格信息 -->
                <div class="order-card">
                    <h2 class="section-title">价格信息</h2>
                    <div class="order-info">
                        <div class="price-details">
                            <div class="price-item">
                                <span class="price-label">订单金额</span>
                                <span class="price-value">¥{{ orderInfo.orderAmount.toFixed(2) }}</span>
                            </div>
                            <div class="price-item">
                                <span class="price-label">平台服务费</span>
                                <span class="price-value">¥{{ orderInfo.platformFee.toFixed(2) }}</span>
                            </div>
                            <div class="price-item" v-if="orderInfo.couponAmount > 0">
                                <span class="price-label">优惠券</span>
                                <span class="price-value discount">-¥{{ orderInfo.couponAmount.toFixed(2) }}</span>
                            </div>
                        </div>
                        <div class="total-price">
                            <span class="total-label">实付金额</span>
                            <span class="total-value">¥{{ calculateTotalPrice() }}</span>
                        </div>
                    </div>
                </div>

                <!-- 用户信息 -->
                <div class="order-card">
                    <h2 class="section-title">用户信息</h2>
                    <div class="order-info">
                        <div class="user-info">
                            <div class="user-item">
                                <div class="user-avatar">
                                    <van-image round width="40" height="40" :src="orderInfo.employerAvatar" />
                                </div>
                                <div class="user-details">
                                    <h3 class="user-name">{{ employerName }}</h3>
                                    <p class="user-role">雇主</p>
                                </div>
                            </div>
                            <div class="user-divider" v-if="orderInfo.workerId">
                                <van-icon name="arrow-down" />
                            </div>
                            <div class="user-item" v-if="orderInfo.workerId">
                                <div class="user-avatar">
                                    <van-image round width="40" height="40" :src="orderInfo.workerAvatar" />
                                </div>
                                <div class="user-details">
                                    <h3 class="user-name">{{ workerName }}</h3>
                                    <p class="user-role">工人</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="action-buttons">
                    <!-- 待支付状态 -->
                    <template v-if="orderInfo.paymentStatus === 0">
                        <van-button class="action-button" type="primary" color="#4f46e5" block @click="goToPayment">
                            去支付
                        </van-button>
                        <van-button class="action-button" plain hairline type="default" block @click="cancelOrder">
                            取消订单
                        </van-button>
                    </template>

                    <!-- 进行中状态 -->
                    <template v-else-if="orderInfo.orderStatus === 1">
                        <van-button class="action-button" type="primary" color="#4f46e5" block @click="completeOrder">
                            完成订单
                        </van-button>
                        <van-button class="action-button" plain hairline type="default" block @click="contactWorker">
                            联系工人
                        </van-button>
                    </template>

                    <!-- 已完成状态 -->
                    <template v-else-if="orderInfo.orderStatus === 2">
                        <van-button class="action-button" type="primary" color="#4f46e5" block @click="rateOrder">
                            评价订单
                        </van-button>
                    </template>
                </div>
            </template>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showDialog } from 'vant'
import network from '../network'

const router = useRouter()
const route = useRoute()
const orderId = ref(Number(route.params.id) || 0)

// 返回上一页
const onClickLeft = () => {
    router.back()
}

// 订单信息
const orderInfo = reactive({
    orderId: 0,
    taskId: 0,
    employerId: 0,
    workerId: 0,
    applicationId: 0,
    taskTitle: '',
    taskAddress: '',
    taskDate: '',
    taskTime: '',
    orderAmount: 0,
    platformFee: 0,
    actualAmount: 0,
    orderStatus: 0,
    paymentStatus: 0,
    startTime: '',
    endTime: '',
    cancelReason: '',
    createTime: '',
    updateTime: '',
    couponAmount: 0,
    // 新增字段
    employerAvatar: '',
    workerAvatar: ''
})

const isLoading = ref(true)
const employerName = ref('未知用户')
const workerName = ref('未知用户')

// 计算总价
const calculateTotalPrice = () => {
    return (orderInfo.actualAmount - orderInfo.couponAmount).toFixed(2)
}

const fetchAvatar = async (userId: number) => {
    try {
        const res: any = await network.getAvatarById(userId);
        if (res.data && res.data.code === 100 && res.data.data && res.data.data.avatarData) {
            // 将获取到的Base64数据赋值
            return res.data.data.avatarData; // 返回Base64数据
        } else {
            console.warn(`获取用户 ${userId} 头像失败: ${res.data?.message}`);
            // 设置为空，由模板处理默认头像
            return ''; // 返回空字符串
        }
    } catch (error) {
        // 出错时设置为空
        console.error(`获取用户 ${userId} 头像异常:`, error);
        return ''; // 返回空字符串
    }
}

// 获取订单信息
const fetchOrderInfo = async () => {
    try {
        if (orderId.value) {
            // 延迟两秒再发送请求，模拟加载效果
            await new Promise(resolve => setTimeout(resolve, 500))

            const res: any = await network.getOrderDetail(orderId.value)
            if (res && res.code === 100) {
                const data = res.data
                Object.assign(orderInfo, {
                    orderId: data.orderId,
                    taskId: data.taskId,
                    employerId: data.employerId,
                    workerId: data.workerId,
                    applicationId: data.applicationId,
                    orderAmount: data.orderAmount,
                    platformFee: data.platformFee,
                    actualAmount: data.actualAmount,
                    orderStatus: data.orderStatus,
                    paymentStatus: data.paymentStatus,
                    startTime: data.startTime,
                    endTime: data.endTime,
                    cancelReason: data.cancelReason,
                    createTime: data.createTime,
                    updateTime: data.updateTime,
                    couponAmount: data.couponAmount || 0
                })

                // 获取任务详情
                await fetchTaskDetail(data.taskId)

                // 获取用户信息
                if (data.employerId) {
                    await fetchUserInfo(data.employerId, 1)
                }

                if (data.workerId) {
                    await fetchUserInfo(data.workerId, 0)
                }
                
                // 获取头像并等待结果
                if (data.employerId) {
                    orderInfo.employerAvatar = await fetchAvatar(data.employerId)
                }
                
                if (data.workerId) {
                    orderInfo.workerAvatar = await fetchAvatar(data.workerId)
                }
            } else {
                showToast('获取订单信息失败')
            }
        } else {
            showToast('订单参数错误')
        }
    } catch (error) {
        console.error('获取订单信息失败:', error)
        showToast('获取订单信息失败，请稍后重试')
    } finally {
        isLoading.value = false
    }
}

// 获取任务详情
const fetchTaskDetail = async (taskId: number) => {
    try {
        if (!taskId) {
            console.error('任务ID为空')
            return
        }

        const res: any = await network.getTaskDetail(taskId)
        if (res.data && res.data.code === 100) {
            const taskData = res.data.data

            // 更新任务相关信息
            orderInfo.taskTitle = taskData.taskTitle || '未知任务'
            orderInfo.taskAddress = taskData.taskAddress || '未知地址'

            // 处理任务时间
            if (taskData.startTime) {
                const timeParts = taskData.startTime.split(' ')
                orderInfo.taskDate = timeParts[0] || ''
                orderInfo.taskTime = timeParts[1] || ''
            } else if (orderInfo.startTime) {
                // 如果任务没有时间，尝试使用订单的开始时间
                const timeParts = orderInfo.startTime.split(' ')
                orderInfo.taskDate = timeParts[0] || ''
                orderInfo.taskTime = timeParts[1] || ''
            }
        } else {
            console.error('获取任务详情失败')
        }
    } catch (error) {
        console.error('获取任务详情失败:', error)
    }
}

// 获取用户信息
const fetchUserInfo = async (userId: number, userType: 1 | 0) => {
    try {
        var res: any = await network.getUserInfo(userId)
        if (res && res.code === 100) {
            var userData = res.data
            if (userType === 1) {
                employerName.value = userData.realname || '未知用户'
            } else {
                workerName.value = userData.realname || '未知用户'
            }
        }
    } catch (error) {
        console.error(`获取${userType === 1 ? '雇主' : '工人'}信息失败:`, error)
    }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
    if (!dateTimeStr) return '未知时间'

    try {
        const date = new Date(dateTimeStr)
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    } catch (e) {
        return dateTimeStr
    }
}

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
    const statuses = {
        '-1': '已取消',
        '0': '待支付',
        '1': '进行中',
        '2': '已完成'
    }
    return statuses[status.toString() as keyof typeof statuses] || '未知状态'
}

// 获取订单状态描述
const getOrderStatusDescription = (status: number) => {
    const descriptions = {
        '-1': '订单已取消',
        '0': '等待工人接单',
        '1': '工人已接单，正在进行中',
        '2': '订单已完成，感谢您的使用'
    }
    return descriptions[status.toString() as keyof typeof descriptions] || ''
}

// 获取订单状态图标
const getOrderStatusIcon = (status: number) => {
    const icons = {
        '-1': 'close',
        '0': 'clock-o',
        '1': 'fire-o',
        '2': 'checked'
    }
    return icons[status.toString() as keyof typeof icons] || 'question-o'
}

// 获取订单状态样式类
const getOrderStatusClass = (status: number) => {
    const classes = {
        '-1': 'status-canceled',
        '0': 'status-pending',
        '1': 'status-processing',
        '2': 'status-completed'
    }
    return classes[status.toString() as keyof typeof classes] || ''
}

// 获取支付状态文本
const getPaymentStatusText = (status: number) => {
    const statuses = {
        '0': '待支付',
        '1': '已支付',
        '2': '已退款'
    }
    return statuses[status.toString() as keyof typeof statuses] || '未知状态'
}

// 获取支付状态类型
const getPaymentStatusType = (status: number) => {
    const types = {
        '0': 'warning',
        '1': 'success',
        '2': 'primary'
    }
    return types[status.toString() as keyof typeof types] || 'default'
}

// 去支付
const goToPayment = () => {
    router.push(`/payment/${orderInfo.orderId}`)
}

// 取消订单
const cancelOrder = () => {
    showDialog({
        title: '取消订单',
        message: '确定要取消此订单吗？',
        showCancelButton: true,
    }).then(() => {
        // 调用取消订单接口
        network.cancelOrder(orderInfo.orderId)
            .then((res: any) => {
                if (res && res.code === 100) {
                    showToast('订单已取消')
                    // 刷新订单信息
                    fetchOrderInfo()
                } else {
                    showToast(res?.message || '取消订单失败')
                }
            })
            .catch((error) => {
                console.error('取消订单失败:', error)
                showToast('取消订单失败，请稍后重试')
            })
    })
}

// 完成订单
const completeOrder = () => {
    showDialog({
        title: '完成订单',
        message: '确定要将此订单标记为已完成吗？',
        showCancelButton: true,
    }).then(() => {
        // 调用完成订单接口
        network.completeOrder(orderInfo.orderId)
            .then((res: any) => {
                if (res && res.code === 100) {
                    showToast('订单已完成')
                    // 刷新订单信息
                    fetchOrderInfo()
                } else {
                    showToast(res?.message || '完成订单失败')
                }
            })
            .catch((error) => {
                console.error('完成订单失败:', error)
                showToast('完成订单失败，请稍后重试')
            })
    })
}

// 联系工人
const contactWorker = () => {
    // 这里可以实现联系工人的功能，如跳转到聊天页面
    showToast('联系工人功能开发中')
}

// 评价订单
const rateOrder = () => {
    // 跳转到评价页面
    router.push(`/rate-order/${orderInfo.orderId}`)
}

// 页面加载时获取数据
onMounted(() => {
    fetchOrderInfo()
})
</script>

<style scoped>
.order-detail-container {
    min-height: 100vh;
    background-color: #f5f7fa;
    padding-top: 46px;
}

.content {
    max-width: 480px;
    margin: 0 auto;
    padding: 16px;
}

.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300px;
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    padding: 20px;
    margin-bottom: 16px;
}

.loading-text {
    margin-top: 16px;
    font-size: 14px;
    color: #64748b;
}

.status-card,
.order-card {
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    padding: 20px;
    margin-bottom: 16px;
}

.status-info {
    display: flex;
    align-items: center;
}

.status-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 48px;
    height: 48px;
    border-radius: 24px;
    margin-right: 16px;
}

.status-icon .van-icon {
    font-size: 24px;
    color: #ffffff;
}

.status-canceled {
    background-color: #ef4444;
}

.status-pending {
    background-color: #f59e0b;
}

.status-processing {
    background-color: #3b82f6;
}

.status-completed {
    background-color: #10b981;
}

.status-details {
    flex: 1;
}

.status-title {
    font-size: 18px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 4px;
}

.status-desc {
    font-size: 14px;
    color: #64748b;
}

.section-title {
    font-size: 18px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 16px;
}

.order-info {
    display: flex;
    flex-direction: column;
}

.task-info {
    padding-bottom: 16px;
}

.task-title {
    font-size: 16px;
    font-weight: 500;
    color: #1e293b;
}

.task-price {
    font-size: 16px;
    font-weight: 600;
    color: #4f46e5;
}

.task-address {
    font-size: 14px;
    color: #64748b;
    margin-bottom: 8px;
}

.task-time {
    display: flex;
    font-size: 14px;
    color: #64748b;
}

.time-item {
    display: flex;
    align-items: center;
    margin-right: 16px;
}

.time-item .van-icon {
    margin-right: 4px;
}

.detail-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    font-size: 14px;
}

.detail-label {
    color: #64748b;
}

.detail-value {
    color: #1e293b;
    font-weight: 500;
}

.price-details {
    margin-bottom: 16px;
}

.price-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 14px;
}

.price-label {
    color: #64748b;
}

.price-value {
    color: #1e293b;
}

.price-value.discount {
    color: #10b981;
}

.total-price {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 12px;
    border-top: 1px solid #e5e7eb;
}

.total-label {
    font-size: 15px;
    font-weight: 500;
    color: #1e293b;
}

.total-value {
    font-size: 20px;
    font-weight: 700;
    color: #4f46e5;
}

.user-info {
    display: flex;
    flex-direction: column;
}

.user-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
}

.user-avatar {
    margin-right: 12px;
}

.user-details {
    flex: 1;
}

.user-name {
    font-size: 16px;
    font-weight: 500;
    color: #1e293b;
    margin-bottom: 4px;
}

.user-role {
    font-size: 14px;
    color: #64748b;
}

.user-divider {
    display: flex;
    justify-content: center;
    padding: 8px 0;
    color: #94a3b8;
}

.action-buttons {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-top: 16px;
}

.action-button {
    height: 44px;
    font-size: 16px;
    border-radius: 22px;
}
</style>